﻿//-----------------------------------------------------------------------
// <copyright file="BaseWebDataSource.cs" company="AFS">
// Copyright (c) AFS. All rights reserved.
//
//    This file is part of Chatbox.
//
//    Chatbox is free software: you can redistribute it and/or modify
//    it under the terms of the GNU Lesser General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    any later version.
//
//    Chatbox is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//    GNU Lesser General Public License for more details.
//
//    You should have received a copy of the GNU Lesser General Public License
//    along with Chatbox. If not, see http://www.gnu.org/copyleft/lesser.html
// </copyright>
//----------------------------------------------------------------------- 

namespace ChatBox.Engine.Web
{
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    using System.Xml;

    using ChatBox.DomainObjects.ResultData;
    using ChatBox.DomainObjects.Settings;
    using ChatBox.Interfaces;
    using ChatBox.Utility;

    /// <summary>
    /// Base class with common functionaity for web data soruces
    /// </summary>
    public abstract class BaseWebDataSource
    {
        #region private and protected data

        /// <summary>
        /// Web Exections that can be ignored
        /// </summary>
        private static readonly List<string> ExceptionMessagePrefixesNotLogged = new List<string>                                                                     
            {
               "The remote name could not be resolved",
               "The operation has timed out",
               "The request was aborted: The operation has timed out",
               "The underlying connection was closed"  
            };

        /// <summary>
        /// Gets or sets a value indicating whether the thread has started
        /// </summary>
        public bool IsStarted
        {
            get;
            protected set;
        }

        /// <summary>
        /// Gets or sets settings data
        /// </summary>
        protected ServerSettingsData ServerSettings
        {
            get;
            set;
        }

        /// <summary>
        /// Gets the sequence of result messages issued
        /// </summary>
        protected int MessageSequence
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets or sets the interface to the error log
        /// </summary>
        protected ILogger Logger
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets  the thread for reading public messages
        /// </summary>
        protected Thread ReadThread
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the interval between reads
        /// </summary>
        protected int ReadInterval
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether the thread should end
        /// </summary>
        protected bool ThreadTerminated
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether the should thread wait between polling the server
        /// </summary>
        protected bool SleepBetweenReads
        {
            get;
            set;
        }

        #endregion

        #region methods

        /// <summary>
        /// Generate a Uri for a node
        /// </summary>
        /// <param name="server">the server name</param>
        /// <param name="nodeId">the node id</param>
        /// <returns>the complete uri for the node</returns>
        public static Uri NodeLink(string server, int nodeId)
        {
            string result = server + "/index.pl?node_id=" + nodeId;
            return new Uri(result);
        }

        private static readonly List<HttpStatusCode> StatusCodesThatAreNotMyProblem = new List<HttpStatusCode>
            {
                    HttpStatusCode.InternalServerError,
                    HttpStatusCode.ServiceUnavailable
            };

        /// <summary>
        /// Indicate if the exception should be logged
        /// </summary>
        /// <param name="ex">the exception</param>
        /// <returns>true if the exception should be logged</returns>
        public static bool LogThisException(Exception ex)
        {
            WebException wex = ex as WebException;
            if (wex != null)
            {
                if ((wex.InnerException != null) && (wex.InnerException is SocketException))
                {
                    // socket timeouts happen when the server is slow 
                    // Do not log the error
                    return false;
                }

                if (wex.Message.StartsWithOneOf(ExceptionMessagePrefixesNotLogged, StringComparison.OrdinalIgnoreCase))
                {
                    // network is down. 
                    // Do not log the error
                    return false;
                }

                // check for return code 500: Internal Server Error and 503: Server Unavailable
                HttpWebResponse httpWebResponse = wex.Response as HttpWebResponse;
                if ((httpWebResponse != null) && (StatusCodesThatAreNotMyProblem.Contains(httpWebResponse.StatusCode)))
                {
                    // Server is not responding
                    // Do not log the error
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Common code to handle an exception
        /// </summary>
        /// <param name="ex">the exception to handle</param>
        protected void HandleWebException(Exception ex)
        {
            if (LogThisException(ex))
            {
                // report the error
                this.ReadThreadOnError(ex);                
            }
        }
        
        /// <summary>
        /// Handle an error in the xml parsing
        /// </summary>
        /// <param name="ex">the exception to handle</param>
        protected void HandleXmlParseException(Exception ex)
        {
            XmlException xmlEx = ex as XmlException;

            if (xmlEx != null)
            {
                // incomplete document retrieved due to timeout. 
                // It happens if the network is slow. Ignore it
                return;
            }

            // report the error
            this.ReadThreadOnError(ex);
        }

        /// <summary>
        /// set the sequence on a sucess operation result
        /// </summary>
        /// <param name="operationResult">the operation result to set sequnce upon</param>
        protected void SetSequence(OperationResult operationResult)
        {
            if (operationResult.Success)
            {
                operationResult.Sequence = this.MessageSequence;
                this.MessageSequence++;
            }
        }
        
        /// <summary>
        /// The thread has called back with an error
        /// </summary>
        /// <param name="ex">the exception</param>
        protected abstract void ReadThreadOnError(Exception ex);

        #endregion
    }
}
